﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Newbe.Build.Psake
{
    internal class Program
    {
        private static async Task Main(string[] args)
        {
            if (args?.Any() == true && args.First() == "init")
            {
                const string buildBatFilename = "build.bat";
                ShowFileMessage(buildBatFilename);
                var buildBatFileContent = await GetAssetFileContent(buildBatFilename);
                await File.WriteAllTextAsync(buildBatFilename, buildBatFileContent);

                const string buildPs1Filename = "build.ps1";
                ShowFileMessage(buildPs1Filename);
                var buildPs1Content = await GetAssetFileContent(buildPs1Filename);
                using (var fileStream = File.Create(buildPs1Filename))
                {
                    using (var streamWriter = new StreamWriter(fileStream, new UTF8Encoding(true)))
                    {
                        await streamWriter.WriteAsync(buildPs1Content);
                    }
                }
            }
        }

        private static void ShowFileMessage(string filename)
        {
            Console.WriteLine(File.Exists(filename)
                ? $"{filename} existed , that will be overwrite"
                : $"{filename} not existed , create a new one");
        }

        private static async Task<string> GetAssetFileContent(string fileName)
        {
            using (var manifestResourceStream =
                typeof(Program).Assembly.GetManifestResourceStream($"Newbe.Build.Psake.Assets.{fileName}"))
            {
                using (var streamReader = new StreamReader(manifestResourceStream))
                {
                    var re = await streamReader.ReadToEndAsync();
                    return re;
                }
            }
        }
    }
}